//
//  CLRMBGColorView.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/8/3.
//

#import "CLRMBGColorView.h"
#import "CLReadMenu.h"
@interface CLRMBGColorView()

@property (nonatomic, strong) NSMutableArray <UIButton *>*items;

@property (nonatomic, strong) UIButton *selectItem;

@end
@implementation CLRMBGColorView

- (void)addSubviews {
    [super addSubviews];
    
    self.backgroundColor = UIColor.clearColor;

    NSInteger count = CL_READ_BG_COLORS.count;

    for (int i = 0; i < count; i++) {
        UIColor *color = CL_READ_BG_COLORS[i];
        UIButton *item = [UIButton buttonWithType:(UIButtonTypeCustom)];
        item.tag = i;
        item.backgroundColor = color;
        item.layer.cornerRadius = CL_SPACE_SA_6;
        item.layer.borderColor = CL_READ_COLOR_MAIN.CGColor;
        item.layer.borderWidth = 0;
        [item addTarget:self action:@selector(clickItem:) forControlEvents:(UIControlEventTouchUpInside)];
        [self addSubview:item];
        [self.items addObject:item];
        
        if (i == CLReadConfigure.sharedInstance.bgColorIndex) {
            [self selectItem:item];
        }
    }
}

- (void)selectItem:(UIButton *)item {

    self.selectItem.layer.borderWidth = 0;

    item.layer.borderWidth = 1.5;

    self.selectItem = item;
}

- (void)clickItem:(UIButton *)item {

    if ([self.selectItem isEqual:item]) { return; }

    [self selectItem:item];

    CLReadConfigure.sharedInstance.bgColorIndex = item.tag;

    [CLReadConfigure.sharedInstance save];

    [self.readMenu.delegate readMenuClickBGColor:self.readMenu];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    NSInteger count = CL_READ_BG_COLORS.count;

    CGFloat w = self.frame.size.width;
    CGFloat h = self.frame.size.height;

    CGFloat itemWH = CL_SPACE_SA_30;
    CGFloat itemY = (h - itemWH) / 2;
    CGFloat itemSpaceW = (w - (CGFloat)(count) * itemWH) / ((CGFloat)(count - 1));

    for (int i = 0;i < count; i++) {
        UIButton *item = self.items[i];
        item.frame = CGRectMake((CGFloat)(i) * (itemWH + itemSpaceW), itemY, itemWH, itemWH);
    }
}

@end
